package com.shop.cloud.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.shop.cloud.auth0.jwt.TokenGenerator;
import com.shop.cloud.auth0.jwt.interfaces.Claim;
import com.shop.cloud.util.CookieManager;
import com.shop.cloud.util.ErrorCode;
import com.shop.cloud.util.MagicConstants;
import com.shop.cloud.util.ResponseUtil;
import com.shop.cloud.util.ServletUtil;

public class AuthAnnotationInterceptor2 extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (handler instanceof HandlerMethod) {
			if(request.getServletPath().equals("/v2/api-docs")){
				return true;
			}
			HandlerMethod methodHandler = (HandlerMethod) handler;
			String token = request.getHeader(MagicConstants.USER_TOKEN);
			if (StringUtils.isEmpty(token)) {
				token = request.getParameter(MagicConstants.USER_TOKEN);
			}
			if (StringUtils.isEmpty(token)) {
				token = new CookieManager(request, null).getCookie(MagicConstants.USER_TOKEN);
			}
			IgnoreAuth annotation = methodHandler.getMethodAnnotation(IgnoreAuth.class);
			// 如果有@IgnoreAuth注解，则不验证token
			if (annotation == null && (StringUtils.isEmpty(token))) {
				writeMessage(request, response);
				return false;
			}
			Map<String, Claim> datas=null;
			if (StringUtils.isNotEmpty(token)&&annotation==null) {
				try {
					datas=TokenGenerator.getClaims(token);
				} catch (Exception e) {
					e.printStackTrace();
					ServletUtil.writeJson(ResponseUtil.error(ErrorCode.TOKEN_EXPIRED), response);
					return false;
				}
				Long userId=datas.get(MagicConstants.SESSION_USER_ID).asLong();
				if (userId==null) {
					writeMessage(request, response);
					return false;
				}
			}
		}
		return true;
	}

	private void writeMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setHeader("sessionstatus", "timeout");
		ServletUtil.writeJson(ResponseUtil.error(ErrorCode.INVALID_ACCESS), response);
	}

}
